package demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import demo.model.Role;
import demo.model.User;

import java.util.Date;

@Path("/role")
public class RoleController extends Controller {
    public void index() {
        render("role.html");
    }

    public void list() {
        int page = getParaToInt("page");
        int limit = getParaToInt("limit");
        String roleName = getPara("roleName");
        //String realName = getPara("realName");
        //Page<User> userPage = User.dao.paginate(page,limit,"select * ", "from sys_user");
        Page<User> userPage = User.dao.template("getList3", new Kv().by("roleName",roleName)).paginate(page,limit);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","操作成功");
        jsonObject.put("count", userPage.getTotalRow());
        jsonObject.put("data", userPage.getList());
        renderJson(jsonObject);
    }

    public void add() {
        Role role = new Role();
        String roleName = getPara("roleName");
        String roleCode = getPara("roleCode");

        role.setRoleName(roleName);
        role.setRoleCode(roleCode);
        role.save();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","保存成功");
        renderJson(jsonObject);
    }

    // 许均益
    public void update() {
        String roleName = getPara("roleName");
        String roleCode = getPara("roleCode");
        int id = getParaToInt("id");
        Role role = Role.dao.findById(id);
        role.setRoleName(roleName);
        role.setRoleCode(roleCode);
        role.update();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","保存成功");
        renderJson(jsonObject);
    }

    //王志元
    public void delete() {
        String id = getPara("id");
        String ids = getPara("ids");
        if(StrKit.notBlank(id)) {
            Role.dao.deleteById(id);
        } else {
            String [] idArra = ids.split(",");
            for (String myId: idArra) {
                Role.dao.deleteById(myId);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","删除成功");
        renderJson(jsonObject);
    }
}
